from django.shortcuts import render
from django.core.cache import cache
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import Car,manufacturer


# Create your views here.
class Carcs(APIView):
    def get(self,request):
        car=Car.objects.all()
        data=[]
        for i in car:
            data.append(
                {
                    'carname':i.carname,
                    'carprice':i.carprice,
                    'carcolor':i.carcolor,
                    'carman':i.carman.manname
                }
            )
        return Response({'coke':'200','msg':'ok','data':data})
    def post(self,request):
        carname=request.data.get('carname')
        carprice=request.data.get('carprice')
        carcolor=request.data.get('carcolor')
        carman=request.data.get('carman')
        Car.objects.create(
            carname=carname,
            carprice=carprice,
            carcolor=carcolor,
            carman=manufacturer.objects.get(id=carman)
        )
        return Response({'coke':'200','msg':'ok'})
class Carcs1(APIView):
    def get(self,request):
        car=manufacturer.objects.all()
        data=[]
        for i in car:
            data.append(
                {
                    'manname':i.manname,
                }
            )
        return Response({'coke':'200','msg':'ok','data':data})
class Carcs2(APIView):
    def get(self,request,pk):
        data=cache.get('stu'+str(pk))
        if data:
            print('数据库中有数据')
            return Response({'coke':'200','msg':'ok','data':data})
        print('数据库中没有')
        car=Car.objects.all()
        data=[]
        for i in car:
            data.append(
                {
                    'carname':i.carname,
                    'carprice':i.carprice,
                    'carcolor':i.carcolor,
                    'carman':i.carman.manname
                }
            )
            cache.set('stu'+str(pk),data,60)
            return Response({'coke':'200','msg':'ok','data':data})
        return Response({'coke':'200','msg':'ok','data':data})